package com.yanqu.road.server.gameplayer.module.activity.wishpool;

import com.yanqu.road.entity.activity.wishpool.WishPoolBigReward;
import com.yanqu.road.entity.activity.wishpool.WishPoolUserData;
import com.yanqu.road.entity.activity.wishpool.WishPoolUserReward;
import com.yanqu.road.entity.enums.eLogMoneyType;
import com.yanqu.road.entity.enums.eRedHotNotifyType;
import com.yanqu.road.entity.enums.eSystemId;
import com.yanqu.road.logic.bussiness.activity.WishPoolActivityBusiness;
import com.yanqu.road.logic.config.GameConfig;
import com.yanqu.road.pb.activity.WishPoolProto;
import com.yanqu.road.pb.worldmessage.WorldMessageProto;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.activity.bulletscreen.BulletScreenModule;
import com.yanqu.road.server.gameplayer.module.base.GeneralModule;
import com.yanqu.road.server.gameplayer.module.player.CurrencyModule;
import com.yanqu.road.server.manger.activity.wishpool.WishPoolMgr;
import com.yanqu.road.server.manger.config.SystemOpenMgr;
import com.yanqu.road.server.manger.log.LogMgr;
import com.yanqu.road.server.pb.WorldMessagePb;
import com.yanqu.road.server.protocol.ClientProtocol;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.utils.LocalDateTimeHelper;
import com.yanqu.road.utils.string.StringUtils;

import java.util.ArrayList;
import java.util.List;

public class WishPoolModule extends GeneralModule {

    private WishPoolUserData userData;

    public WishPoolModule(GamePlayer player) {
        super(player);
    }

    @Override
    public boolean loadData() {
        if (SystemOpenMgr.systemOpen(player, eSystemId.WishPoolActivity.getValue())) {
            int inTimeActivityId = WishPoolMgr.getInShowTimeActivityId();
            if (inTimeActivityId == 0) {
                userData = null;
                return true; // 没有活动
            }
            userData = WishPoolActivityBusiness.getWishPoolData(player.getUserId(), inTimeActivityId);
            if (userData == null) {
                initUserData(inTimeActivityId);
            }
        }
        return true;
    }

    @Override
    public boolean afterLoadData() {
        return true;
    }

    @Override
    public boolean saveData() {
        if (userData == null) {
            return true; // 没有活动
        }
        if (userData.isInsertOption()) {
            WishPoolActivityBusiness.addWishPoolData(userData);
        } else if (userData.isUpdateOption()) {
            WishPoolActivityBusiness.updateWishPoolData(userData);
        }
        return true;
    }

    @Override
    public void afterLogin() {
        if (userData == null) {
            return; // 没有活动
        }
        resetOneDay();
        notifyRedHot();
    }

    /**
     * 推送许愿池的红点
     */
    public void notifyRedHot() {
        // 有剩余许愿次数
        if (userData != null && userData.getWishTimes() < GameConfig.WISH_POOL_ONE_DAY_TIMES) {
            WorldMessageProto.RedHotNotifyMsg.Builder builder = WorldMessagePb.parseRedHotNotifyMsg(eRedHotNotifyType.WishPoolCanWish.getValue(), 1, "");
            player.sendPacket(ClientProtocol.U_RED_HOT_NOTIFY, builder);
        }
    }

    public WishPoolUserData getUserData() {
        return userData;
    }

    /**
     * 许愿
     *
     * @return list[0]：结果，0次数不足，1普通奖励，2大奖励；list[1]：获得的奖励
     */
    public List<String> doWish() {
        List<String> result = new ArrayList<>(2);

        // 次数
        if (userData.getWishTimes() >= GameConfig.WISH_POOL_ONE_DAY_TIMES) {
            result.add("0");
            return result;
        }
        userData.setWishTimes(userData.getWishTimes() + 1);
        userData.setWishValue(userData.getWishValue() + WishPoolMgr.wishPoolConfig.getOneTimesWishValue());

        String reward = "";
        List<WishPoolUserReward> userRewardList = userData.getWishRewardList();
        List<WishPoolBigReward> bigRewardList = WishPoolMgr.getBigRewardList();
        // 判断大奖
        for (int i = 0; i < userRewardList.size(); i++) {
            if (!userRewardList.get(i).isGetReward()) {
                if (bigRewardList.get(i).getWishValue() <= userData.getWishValue()) {
                    reward = StringUtils.isNullOrEmpty(reward) ?
                            userRewardList.get(i).getReward()
                            : reward + ";" + userRewardList.get(i).getReward(); // 兼容一次许愿拿多个大奖
                    userRewardList.get(i).setGetReward(true);
                    userData.setUpdateOption();
                } else {
                    break;
                }
            }
        }
        // 判断小奖
        if (StringUtils.isNullOrEmpty(reward)) {
            reward = WishPoolMgr.randomCommonReward();
            result.add("1");
        } else {
            result.add("2");
        }

        // 发奖
        player.getModule(CurrencyModule.class).addCurrency(reward, eLogMoneyType.Activity, eLogMoneyType.WishPoolWishAction);

        // 日志
        LogMgr.addLogWishPoolValue(userData.getActivityId(), userData.getUserId(), WishPoolMgr.wishPoolConfig.getOneTimesWishValue(), userData.getWishValue());

        result.add(reward);
        return result;
    }

    /**
     * 获取用户许愿池数据
     */
    public WishPoolProto.WishPoolDataMsg.Builder getWishPoolDataMsg() {
        // 组装奖励项
        List<WishPoolProto.WishPoolRewardMsg> rewardMsgList = new ArrayList<>();
        List<WishPoolUserReward> userRewardList = userData.getWishRewardList();
        List<WishPoolBigReward> bigRewardList = WishPoolMgr.getBigRewardList();
        for (int i = 0; i < bigRewardList.size(); i++) {
            WishPoolProto.WishPoolRewardMsg.Builder rewardBuilder = WishPoolProto.WishPoolRewardMsg.newBuilder();
            rewardBuilder.addAllOptionalRewardList(bigRewardList.get(i).getRewardList());
            rewardBuilder.setNeedWishValue(bigRewardList.get(i).getWishValue());
            if (i < userRewardList.size()) {
                rewardBuilder.setIsGetReward(userRewardList.get(i).isGetReward());
                rewardBuilder.setUserReward(userRewardList.get(i).getReward());
            } else {
                rewardBuilder.setIsGetReward(false); // 用户未设置奖励，那肯定未领奖
            }
            rewardMsgList.add(rewardBuilder.build());
        }
        // 返回结果
        WishPoolProto.WishPoolDataMsg.Builder builder = WishPoolProto.WishPoolDataMsg.newBuilder();
        builder.addAllRewardList(rewardMsgList);
        builder.setWishValue(userData.getWishValue());
        // 服务端存 已许愿次数，给客户端 剩余许愿次数
        builder.setWishTimes(GameConfig.WISH_POOL_ONE_DAY_TIMES - userData.getWishTimes());
        return builder;
    }

    /**
     * 设置许愿奖励
     *
     * @return 0：成功，N：错误码
     */
    public int setWishRewards(String newRewards) {
        List<String> newRewardList = StringUtils.stringToStringList(newRewards, "\\|");
        List<WishPoolUserReward> userRewardList = userData.getWishRewardList();
        List<WishPoolBigReward> configRewardList = WishPoolMgr.getBigRewardList();

        // 奖励数量判断
        if (configRewardList.size() != newRewardList.size()) {
            return GameErrorCode.E_ACTIVITY_WISH_POOL_REWARD_COUNT_ERROR;
        }

        // 已领奖的不能修改
        for (int i = 0; i < userRewardList.size(); i++) {
            String tmpNewReward = newRewardList.get(i);
            WishPoolUserReward tmpUserReward = userRewardList.get(i);
            if (!StringUtils.stringEquals(tmpUserReward.getReward(), tmpNewReward)
                    && tmpUserReward.isGetReward()) {
                return GameErrorCode.E_ACTIVITY_WISH_POOL_REWARD_SHOULD_NO_RECEIVE;
            }
        }

        // 奖励是否在配置中
        for (int i = 0; i < newRewardList.size(); i++) {
            String tmpNewReward = newRewardList.get(i);
            List<String> tmpOptionalRewardList = configRewardList.get(i).getRewardList();
            if (!tmpOptionalRewardList.contains(tmpNewReward)) {
                return GameErrorCode.E_ACTIVITY_WISH_POOL_REWARD_NO_EXIST;
            }
        }

        //修改奖励
        int oldSize = userRewardList.size();
        for (int i = 0; i < newRewardList.size(); i++) {
            // 未领奖的旧数据：修改原来值
            if (i < oldSize && !userRewardList.get(i).isGetReward()) {
                userRewardList.get(i).setReward(newRewardList.get(i));
            } else if (i >= oldSize) {
                // 新数据：新增一项
                WishPoolUserReward tmpReward = new WishPoolUserReward();
                tmpReward.setReward(newRewardList.get(i));
                tmpReward.setGetReward(false);
                userRewardList.add(tmpReward);
            }
        }
        userData.setUpdateOption();
        return 0;
    }

    /**
     * 初始化用户数据
     */
    public void initUserData(int activityId) {
        userData = new WishPoolUserData();
        userData.setUserId(player.getUserId());
        userData.setActivityId(activityId);
        userData.setWishValue(0);
        userData.setResetTime(System.currentTimeMillis());
        userData.setWishTimes(0);
        userData.setWishRewardList(new ArrayList<>());
        userData.setInsertOption();
        player.getModule(BulletScreenModule.class).initUserData(activityId);
        player.getModule(BulletScreenModule.class).syncUserData();
    }

    /**
     * 每日重置
     *
     * @return true：重置成功，false：不需要重置
     */
    public synchronized boolean resetOneDay() {
        if (SystemOpenMgr.systemOpen(player, eSystemId.WishPoolActivity.getValue())) {
            long today = LocalDateTimeHelper.getZeroTimeTimeStamp();
            long lastResetDay = LocalDateTimeHelper.getZeroTimeTimeStamp(userData.getResetTime());
            if (today > lastResetDay) {
                userData.setWishTimes(0);
                userData.setResetTime(System.currentTimeMillis());
                return true;
            }
        }
        return false;
    }

    /**
     * 是否设置奖励
     */
    public boolean isRewardSet() {
        return userData.getWishRewardList().size() == WishPoolMgr.getBigRewardList().size();
    }

    public void initSystem() {
        int inTimeActivityId = WishPoolMgr.getInShowTimeActivityId();
        if (inTimeActivityId == 0) {
            userData = null;
            return; // 没有活动
        }
        userData = WishPoolActivityBusiness.getWishPoolData(player.getUserId(), inTimeActivityId);
        if (userData == null) {
            initUserData(inTimeActivityId);
        }
    }

}